package com.hudongwx.godoffood.activity.home_activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.MainActivity;
import com.hudongwx.godoffood.fragment.ShoppingFragment;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.DBUtils.DbOpenUtils;
import com.hudongwx.godoffood.utils.DBUtils.ShoppingCar;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

@ContentView(R.layout.activity_food_goods_page)
public class FoodGoodsPageActivity extends AppCompatActivity {
    private String TAG = "FoodGoodsPageActivity";
    @ViewInject(R.id.goods_content_type)
    RadioGroup radioGroup;
    @ViewInject(R.id.goods_content_type1)
    RadioButton radioButton1;
    @ViewInject(R.id.goods_content_type2)
    RadioButton radioButton2;

    @ViewInject(R.id.goods_content_img)
    ImageView goodsImg;
    @ViewInject(R.id.goods_content_name)
    TextView goodsName;
    @ViewInject(R.id.goods_content_title)
    TextView goodsTitle;
    @ViewInject(R.id.goods_content_price)
    TextView goodsPrice;
    @ViewInject(R.id.goods_content_parameter)
    TextView goodsParameter;
    @ViewInject(R.id.goods_content_web)
    WebView webView;

    @ViewInject(R.id.goods_sale_out2)
    ImageView saleOut;

    @ViewInject(R.id.goods_num)
    TextView goodsNum;
    @ViewInject(R.id.goods_content_car_num)
    TextView carNum;
    private String id;
    private String shareTitle,shareContent,type,goodsID,imgUrl;
    private int price,state;

    private DbManager dbManager;//获取一个数据库管理器
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        dbManager= DbOpenUtils.getShoppingDb();
        //显示购物车商品数量
        List<ShoppingCar> all = null;
        try {
            all = dbManager.findAll(ShoppingCar.class);
            if (all!=null){
                carNum.setVisibility(View.VISIBLE);
                int count = 0;
                for (ShoppingCar sc : all) {
                    count += sc.getNum();
                }
                carNum.setText(count+"");
            }else {
                carNum.setVisibility(View.INVISIBLE);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }


        //获取产品id数组
        final String[] productIDs = getIntent().getStringArrayExtra("productID");

        //设置默认选中项
        radioGroup.check(radioGroup.getChildAt(0).getId());
        radioButton1.setSelected(true);
        //加载产品数据
        loadProductContent(productIDs[0]);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.goods_content_type1:
                        radioButton1.setSelected(true);
                        radioButton2.setSelected(false);
                        loadProductContent(productIDs[0]);
                        break;
                    case R.id.goods_content_type2:
                        radioButton1.setSelected(false);
                        radioButton2.setSelected(true);
                        loadProductContent(productIDs[1]);
                        break;
                }
            }
        });
    }

    //加载商品数据
    public void loadProductContent(String productID){
        id = productID;
        RequestParams params = new RequestParams(API.getGoodsContent(productID));
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                Log.i(TAG, "onSuccess: 数据加载成功"+result);
                try {
                    JSONObject data = result.getJSONObject("Data");
                    String img = data.getJSONArray("CustProductPhotos").getJSONObject(0).getString("url");
                    //分享标题
                    shareTitle = data.getString("ProductName");
                    //f分享内容
                    shareContent = data.getString("ZMShortDescribes");
                    //设置商品图片
                    x.image().bind(goodsImg,img);
                    //判断是否售完  3表示有货、4表示售罄
                    state = data.getInt("DPState");
                    if (state==3){
                        saleOut.setVisibility(View.INVISIBLE);
                    }
                    //获取当前商品显示页的规格
                    type = data.getString("Spec");
                    //获取商品id
                    goodsID = data.getString("ProductID");
                    //获取商品价格
                    price = data.getInt("UnitPrice");
                    //获取商品图片
                    imgUrl = data.getString("ImgUrl");


                    goodsTitle.setText(data.getString("ProductName"));
                    goodsName.setText(data.getString("ShortName"));
                    goodsPrice.setText("￥"+data.getString("UnitPrice")+"0");
                    goodsNum.setText(data.getInt("PurchaseQuantity")+"");
                    radioButton1.setText(data.getJSONArray("RelevantSpecs").getJSONObject(0).getString("Spec"));
                    radioButton2.setText(data.getJSONArray("RelevantSpecs").getJSONObject(1).getString("Spec"));
                    //设置产品参数
                    String param = data.getString("ProductAttributes");
                    String param2 = param.replaceAll("\\#\\#\\#","");
                    goodsParameter.setText(param2);
                    //webview加载设置
                    String webUrl = data.getString("AppDescribe");
                    String webHTML = "<html><head><style>img{height=auto;}</style></head><body>"+webUrl+"</body></html>";
                    webView.loadDataWithBaseURL(null,webHTML,"text/html","utf-8",null);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //减少商品数量
    @Event(R.id.goods_num_reduce)
    private void reduce(View view){
        int num = Integer.parseInt((goodsNum.getText()+""));
        Log.i(TAG, "reduce: "+num);
        if (num>1){
            num--;
            goodsNum.setText(num+"");
        }
    }
    //增加商品数量
    @Event(R.id.goods_num_add)
    private void add(View view){
        int num = Integer.parseInt((goodsNum.getText()+""));
        num++;
        goodsNum.setText(num+"");
    }

    @Event(R.id.goods_content_back)
    private void back(View view){
        super.onBackPressed();
    }

    //跳转购物车
    @Event(R.id.goods_to_shopping_car)
    private void toShoppingCar(View view){
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("toShoppingCar",1);
        startActivity(intent);
//        try {
//            List<ShoppingCar> cars = dbManager.findAll(ShoppingCar.class);
//            for (ShoppingCar car : cars) {
//                Log.i(TAG, "toShoppingCar: "+car.getProductID()+":"+car.getNum());
//            }
////            dbManager.delete(ShoppingCar.class);

//        } catch (DbException e) {
//            e.printStackTrace();
//        }
    }

    //添加到购物车
    @Event(R.id.goods_content_add_car)
    private void addShoppingCar(View view){
        //如果有货就添加到购物车
        if (state ==3){
            try {
                boolean flag = false;

                String name = goodsName.getText()+"";
                int num = Integer.parseInt((goodsNum.getText()+""));

                //取出所有数据
                List<ShoppingCar> list = dbManager.findAll(ShoppingCar.class);
                if (list!=null){
                    Log.i(TAG, "addShoppingCar: !=null"+list.size());
                    for (int i = 0; i < list.size(); i++) {
                        //通过商品id判断之前是否添加过该商品
                        if (list.get(i).getProductID().equals(goodsID)){
                            flag = true;
                        }
                    }
                }
                Log.i(TAG, "addShoppingCar: "+flag+":"+goodsID);
                //如果之前添加过这个商品，就 更新商品数量
                if (flag){
                    Selector<ShoppingCar> selector = dbManager.selector(ShoppingCar.class).where("productID", "=", goodsID);
                    ShoppingCar car = selector.findFirst();
                    Log.i(TAG, "addShoppingCar: "+car.getNum()+"："+num+":"+car.getType());

                    //更新商品数量
                    car.setNum(car.getNum()+num);
                    dbManager.update(car);
                }else {//没添加过就直接添加
                    dbManager.save(new ShoppingCar(goodsID,name,price,type,num,imgUrl));
                }


                //显示购物车商品数量
                List<ShoppingCar> all = dbManager.findAll(ShoppingCar.class);
                int count = 0;
                for (ShoppingCar sc : all) {
                    count += sc.getNum();
                }
                carNum.setText(count+"");

                Toast.makeText(FoodGoodsPageActivity.this,"添加成功！",Toast.LENGTH_SHORT).show();
            } catch (DbException e) {
                e.printStackTrace();
            }
        }else {
            Toast.makeText(FoodGoodsPageActivity.this,"没货了！",Toast.LENGTH_SHORT).show();
        }

    }




    @Event(R.id.goods_content_share)
    private void showShare(View view) {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//        oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(shareTitle);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(API.getProductShareUrl(id));
        // text是分享文本，所有平台都需要这个字段
        oks.setText(shareContent);
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        //oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(API.getProductShareUrl(id));
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        // oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(shareTitle);
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }
}
